import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Modal,
  Input,
  Row,
  Col,
  message,
  Divider,
  Dropdown,
  Menu,
  Select,
} from 'antd';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import HOCSelect from '@/components/AntDesign/Select';
import { checkPermissions } from '@/utils/authority';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import TextOverFlow from '../../components/TextOverFlow';

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;
@connect(({ login, businessscope, loading }) => ({
  baseUser: login.baseUser,
  pageData: businessscope.pageData,
  loading: loading.effects['businessscope/getPageList'],
  formFieldsValue: businessscope.formFieldsValue,
  valuesArr: businessscope.valuesArr,
  supplyNameList: businessscope.supplyNameList,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedRows: [],
      selectedRowKeys: [],
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'businessscope/getMgrSuppListByUser',
      payload: {},
    });
    this.getInitialList();
  }

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
    } = this.props;
    if (location.queryParam) {
      dispatch({
        type: 'businessscope/updateModelData',
        payload: { formFieldsValue: location.queryParam },
      });
    }
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = () => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'businessscope/updateModelData',
          payload: {
            formFieldsValue: values,
          },
        });
        this.searchList(this.processFormData(values));
      }
    });
  };

  // 查询
  searchList = (formFieldsValue, currentPage = 1, pageSize = 10, isClear = true) => {
    const { dispatch } = this.props;
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }
    const pageArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pageArg,
    };

    dispatch({
      type: 'businessscope/updateModelData',
      payload: {
        values,
      },
    });

    dispatch({
      type: 'businessscope/getPageList',
      payload: values,
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'suppCode') {
        tempFieldsValue[key] = (tempFieldsValue[key] && tempFieldsValue[key].trim()) || null;
      }
      if (tempFieldsValue[key] && tempFieldsValue[key].key) {
        formFieldsValue[key] =
          tempFieldsValue[key].key === undefined ? null : tempFieldsValue[key].key;
      } else {
        formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
      }
    });
    if (formFieldsValue.suppCode === '') {
      formFieldsValue.suppCode = null;
    }
    return formFieldsValue;
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { formFieldsValue } = this.props;
    this.searchList(
      this.processFormData(formFieldsValue),
      pagination.current,
      pagination.pageSize,
      false
    );
  };

  // 重置查询
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'businessscope/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
  };

  // 查看详情
  goDetails = (id, name) => {
    const {
      location: { pathname },
    } = this.props;
    const tempUrl = pathname.split('/index')[0];
    router.push(`${tempUrl}/detail?suppId=${id}&name=${name}`);
  };

  // 删除
  delList = suppId => {
    this.setState({ selectedRowKeys: [suppId] });
    const {
      pageData: { pagination },
      dispatch,
      formFieldsValue,
    } = this.props;
    confirm({
      title: '你确定要删除此条供应商信息吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'businessscope/deleteBusiness',
          payload: {
            suppIdList: [suppId],
          },
        }).then(res => {
          if (res.success) {
            message.success('删除成功！');
            this.searchList(
              this.processFormData(formFieldsValue),
              pagination.current,
              pagination.pageSize
            );
          } else {
            message.warning('删除失败！');
          }
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  render() {
    const { selectedRows, selectedRowKeys } = this.state;
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      pageData,
      loading,
      supplyNameList,
    } = this.props;
    const formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
    const columns = [
      {
        title: '供应商编号',
        dataIndex: 'suppCode',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '供应商名称',
        dataIndex: 'name',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '地区数量',
        dataIndex: 'areaSize',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        align: 'center',
      },
      {
        title: '供应商类型',
        dataIndex: 'typeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        align: 'center',
      },
      {
        title: '操作',
        dataIndex: 'companyDes',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => {
          const { baseUser } = this.props;
          const { userType } = baseUser;
          // 如果是平台管理员(用户类型1)登录 可以修改,删除供应商类型 2、3
          // 如果是公司管理员(用户类型2) 只能修改,删除供应商类型 4
          // 针对平台供应商的业务范围不可修改，需联系平台管理员进行修改。
          return (
            <div>
              {userType !== 1 ? (
                <span>
                  <a onClick={() => this.goDetails(record.suppId, record.name)}>查看</a>
                  {record.type === 4
                    ? checkPermissions('business:suppBusiScope:update') &&
                      checkPermissions('business:suppBusiScope:delete') && (
                        <>
                          <Divider type="vertical" />
                          <Dropdown
                            overlay={
                              <Menu>
                                {checkPermissions('business:suppBusiScope:update') && (
                                  <Menu.Item>
                                    <a
                                      onClick={() =>
                                        router.push(
                                          `/supplymanage/busiscope/update?suppId=${
                                            record.suppId
                                          }&name=${record.name}&corpId=${record.corpId}`
                                        )
                                      }
                                    >
                                      修改
                                    </a>
                                  </Menu.Item>
                                )}
                                {checkPermissions('business:suppBusiScope:delete') && (
                                  <Menu.Item>
                                    <a onClick={() => this.delList(record.suppId)}>删除</a>
                                  </Menu.Item>
                                )}
                              </Menu>
                            }
                          >
                            <a>
                              更多 <DownOutlined />
                            </a>
                          </Dropdown>
                        </>
                      )
                    : null}
                </span>
              ) : (
                <div>
                  <a onClick={() => this.goDetails(record.suppId, record.name)}>查看</a>
                  {record.type === 2 || record.type === 3
                    ? checkPermissions('business:suppBusiScope:update') &&
                      checkPermissions('business:suppBusiScope:delete') && (
                        <>
                          <Divider type="vertical" />
                          <Dropdown
                            overlay={
                              <Menu>
                                {checkPermissions('business:suppBusiScope:update') && (
                                  <Menu.Item>
                                    <a
                                      onClick={() =>
                                        router.push(
                                          `/supplymanage/busiscope/update?suppId=${
                                            record.suppId
                                          }&name=${record.name}&corpId=${record.corpId}`
                                        )
                                      }
                                    >
                                      修改
                                    </a>
                                  </Menu.Item>
                                )}
                                {checkPermissions('business:suppBusiScope:delete') && (
                                  <Menu.Item>
                                    <a onClick={() => this.delList(record.suppId)}>删除</a>
                                  </Menu.Item>
                                )}
                              </Menu>
                            }
                          >
                            <a>
                              更多 <DownOutlined />
                            </a>
                          </Dropdown>
                        </>
                      )
                    : null}
                </div>
              )}
            </div>
          );
        },
      },
    ];
    const renderSimpleForm = (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="供应商编号">
              {getFieldDecorator('suppCode', {
                initialValue: formFieldsValue.suppCode,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            {/* <FormItem {...formItemLayout} label="供应商名称">
              {getFieldDecorator('suppId', {
                initialValue: formFieldsValue.suppId,
              })(<Supplier allowClear />)}
            </FormItem> */}
            <FormItem {...formItemLayout} label="供应商名称">
              {getFieldDecorator('suppId', {
                initialValue: formFieldsValue.suppId,
              })(
                <HOCSelect
                  placeholder="请输入"
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                  allowClear
                >
                  {supplyNameList.map(options => (
                    <Option key={options.suppId} title={options.name}>
                      {options.name}
                    </Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={this.searchBtnList}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{renderSimpleForm}</div>
        </Card>
        <Card className={styles.tableCard}>
          <Authorized authority="business:suppBusiScope:insert" noMatch={null}>
            <Button
              type="primary"
              onClick={() => router.push('/supplymanage/busiscope/add')}
              style={{ marginBottom: 16, marginRight: 8 }}
            >
              <PlusOutlined />
              新增
            </Button>
          </Authorized>
          <Authorized authority="business:suppBusiScope:batchInsert" noMatch={null}>
            <Button onClick={() => router.push(`/supplymanage/busiscope/batch`)}>批量新增</Button>
          </Authorized>
          <div>
            <StandardTable
              selectedRows={selectedRows}
              selectedRowKeys={selectedRowKeys}
              loading={loading}
              data={pageData}
              rowKey="suppId"
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
